<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/6/8/008
 * Time: 23:15
 */

namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
class WxNotify extends \WxPayNotify
{
   public function NotifyProcess($data, &$msg)
   {
       //重写此类方法
       //return parent::NotifyProcess($data, $msg); // TODO: Change the autogenerated stub
       //库存检查
       if($data['result_code']=='SUCCESS')
       {
           $orderNo = $data['out_trade_no'];
           //事务处理的开始
           Db::startTrans();
           try{
               //检查订单id lock是对查询语句枷锁
               $order = OrderModel::where('order_no','=',$orderNo)->lock(true)->find();
               //通过状态来检查
               if($order->status ==1){
                   $service = new OrderService();
                   $stockStatus = $service->checkOrderStock($order->id);
                   //如果通过，库存量改变状态
                   if( $stockStatus['pass']){
                       //传入order的id并返回true
                       $this->updateOrderStatus($order->id,true);
                       //注意传参数
                       $this->reduceStock($stockStatus);
                   }else{
                       $this->updateOrderStatus($order->id,false);
                   }
               }
               Db::commit();
               return true;
           }catch (Exception $ex)
           {
               //出错之前回滚
               Db::rollback();
               Log::error($ex);
                return false;
           }
       }else{
           return true;
       }
   }

    //减少库存量
    private function reduceStock($stockStatus)
    {
        foreach ($stockStatus['pStatusArray'] as $singlePStatus)
        {
            //$singlePStatus['count']数量
            Product::where('id','=',$singlePStatus['id'])->setDec('stock',$singlePStatus['count']);
        }
    }
   //更新的方法
    private function updateOrderStatus($orderID,$success)
    {
        //判断成功返回的状态
        $status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        //更新方法
        OrderModel::where('id','=',$orderID)->update(['status'=>$status]);
    }


}